package com.month.security.config;

import com.month.security.exception.AuthenticationEntryPointImpl;
import com.month.security.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Configuration
public class SecurityConfig {

    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;


    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;


    @Autowired
    UserDetailsService userDetailsService;

    /**
     * AuthenticationManager认证决策中心
     * ProviderManager 管理认证提供者
     * DaoAuthenticationProvider 身份验证提供者--基于数据库认证
     * bCryptPasswordEncoder 密码加密方式
     * 身份验证管理
     * @return
     */
    @Bean
    public AuthenticationManager authenticationManager() {
        DaoAuthenticationProvider authenticationManager = new DaoAuthenticationProvider();
        authenticationManager.setUserDetailsService(userDetailsService);
        authenticationManager.setPasswordEncoder(bCryptPasswordEncoder());
        return new ProviderManager(authenticationManager);
    }



    /**
     * 密码加密方式
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder()
    {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth
                        // 放行登录和版本检查接口
                        .requestMatchers(
                                "/login",
                                "/spring-version"
                        ).permitAll()
                        // 精确放行 Knife4j 和 SpringDoc 相关路径
                        .requestMatchers(
                                "/doc.html",                // Knife4j 文档页面
                                "/v3/api-docs/**",          // OpenAPI 文档 JSON
                                "/webjars/**",              // WebJars 静态资源
                                "/swagger-ui/**",           // Swagger UI 静态资源
                                "/swagger-ui.html",         // Swagger UI 页面
                                "/swagger-resources/**",    // Swagger 资源文件
                                "/favicon.ico",             // 网站图标
                                "/swagger-resources",       // Swagger 资源
                                "/v3/api-docs"            // OpenAPI 文档
                        ).permitAll()
                        // 其他请求需要认证
                        .anyRequest().authenticated()
                )
                .exceptionHandling(exception ->
                        exception.authenticationEntryPoint(unauthorizedHandler)
                )
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

}
